import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class RefreshDemoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return RefreshDemoPageState();
  }
}

class RefreshDemoPageState extends State<RefreshDemoPage> {
  final int pageSize = 30;

  ScrollController controller = ScrollController();

  List<String> dataList = new List();

  bool disposed = false;

  final GlobalKey<RefreshIndicatorState> refreshKey = new GlobalKey();

  // 刷新事件
  Future refresh() async {
    print('refresh');
    // 延迟2秒钟
    await Future.delayed(Duration(seconds: 2));
    dataList.clear();
    for (int i = 0; i < pageSize; i++) {
      dataList.add("refresh");
    }
    if (disposed) {
      return;
    }
    setState(() {});
  }

  Future loadMore() async {
    print('loadMore');
    await Future.delayed(Duration(seconds: 0));
    for (int i = 0; i < pageSize; i++) {
      dataList.add("loadMore");
    }
    if (disposed) {
      return;
    }
    setState(() {});
  }

  void initState() {
    super.initState();
    controller.addListener(() {
      if (controller.position.pixels == controller.position.maxScrollExtent) {
        loadMore();
      }
    });

//    Future.delayed(Duration(seconds: 0), () {
//      refreshKey.currentState.show();
//    });
  }

  @override
  void dispose() {
    disposed = true;
    super.dispose();
  }

  Widget _scrollList() {
    return RefreshIndicator(
//        key: refreshKey,
        onRefresh: refresh,
        child: Container(
          margin: EdgeInsets.all(10),
          child: ListView.builder(
            ///保持ListView任何情况都能滚动，解决在RefreshIndicator的兼容问题。
            physics: const AlwaysScrollableScrollPhysics(),
            controller: controller,
            itemBuilder: (context, index) {
              if (index == dataList.length) {
                return Container(
                  margin: EdgeInsets.all(10),
                  child: Align(
//                    child: CircularProgressIndicator(),
                  child: Text('123123'),
                  ),
                );
              }
              return Card(
                child: Container(
                  height: 60,
                  padding: EdgeInsets.only(left: 10),
                  alignment: Alignment.centerLeft,
                  child: Text(
                      "Item ${dataList.length > 0 ? dataList[index] : ''} $index"),
                ),
              );
            },
            itemCount: (dataList.length >= pageSize)
                ? dataList.length + 1
                : dataList.length,
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Text('刷新例子')), body: _scrollList());
  }
}
